package cn.bonoon.kernel.web.views;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

public class DateConverter implements Converter<String, Date> {

	private SimpleDateFormat datetimeFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat datetimeFormat2 = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm");
	@Override
	public Date convert(String text) {
		if (StringUtils.hasText(text)) {
			int count = StringUtils.countOccurrencesOf(text, "-");
			int count2 = StringUtils.countOccurrencesOf(text, ":");
			try {
				if (text.indexOf(":") == -1 && count == 2 && text.length() >= 8
						&& text.length() <= 10) {
					return(this.dateFormat.parse(text));
				} else if (text.indexOf(":") > 0 && count == 2 && count2 == 2
						&& text.length() >= 13 && text.length() <= 19) {
					return(this.datetimeFormat.parse(text));
				} else if ((text.indexOf(":") > 0 && count == 2 && count2 == 1
						&& text.length() >= 13 && text.length() <= 16)) {
					return(this.datetimeFormat2.parse(text));
				} else {
					throw new IllegalArgumentException(
							"Could not parse date, date format is error ");
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException(
						"Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		} else {
			return null;
		}
	}

}
